import frappe

def before_uninstall():
    """WMS卸载前处理：清理ERPNext中的WMS工作空间"""
    print("🧹 开始清理ERPNext中的WMS工作空间...")
    try:
        # 查找并删除WMS相关工作空间
        workspaces_to_delete = [
            "WMS",
            "WMS_ERPNext",
            "wmscopy",
            "仓储管理"
        ]
        deleted_count = 0
        for workspace_name in workspaces_to_delete:
            if frappe.db.exists("Workspace", {"name": workspace_name, "app": "erpnext"}):
                try:
                    frappe.delete_doc("Workspace", workspace_name, ignore_permissions=True)
                    deleted_count += 1
                    print(f"✅ 已删除工作空间: {workspace_name}")
                except Exception as e:
                    print(f"⚠️ 删除工作空间 {workspace_name} 失败: {str(e)}")
        if deleted_count > 0:
            frappe.db.commit()
            print(f"✅ 共清理了 {deleted_count} 个WMS工作空间")
        else:
            print("ℹ️ 未找到需要清理的WMS工作空间")
    except Exception as e:
        print(f"❌ 清理过程中发生错误: {str(e)}")
        frappe.log_error(str(e), "WMS Workspace Cleanup Error")